package cn.edu.bjut.homework.chapter7;

import cn.edu.bjut.homework.chapter3.Date;
import cn.edu.bjut.homework.chapter4.Cpc;
import cn.edu.bjut.homework.chapter4.Ipc;
import cn.edu.bjut.homework.chapter5.Patent;
import cn.edu.bjut.homework.chapter6.ChapterSix;
import cn.edu.bjut.homework.chapter6.Corpus;
import com.formdev.flatlaf.FlatLightLaf;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

public class CorpusGUI {
    private JFrame frm;
    private JTable table;
    private JTextField IDText;
    private JTextField dateText;
    private JTextField ipcText;
    private JTextField cpcText;
    Corpus corpus = new Corpus();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
//                    try {
//                        UIManager.setLookAndFeel( new FlatLightLaf() );
//                    } catch( Exception ex ) {
//                        System.err.println( "Failed to initialize LaF" );
//                    }
                    CorpusGUI window = new CorpusGUI();
                    window.frm.setVisible(true);
                    window.frm.pack();
//                    window.frm.setSize(900, 500);
                    window.frm.setLocationRelativeTo(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public CorpusGUI() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    protected void initialize() {
        frm = new JFrame();
        frm.setTitle("专利管理系统");
//        frm.setUndecorated(true);
//        frm.setBounds(10, 10, 900, 500);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setLayout(new GridBagLayout());

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.BOTH;

        JLabel IDLabel = new JLabel("ID：");
        constraints.gridx = 0;
        constraints.gridwidth = 1;
        constraints.weightx = 1;
        frm.add(IDLabel, constraints);
        IDText = new JTextField();
        IDText.setColumns(5);
        constraints.gridx = 1;
        constraints.gridwidth = 1;
        constraints.weightx = 1;
        frm.add(IDText, constraints);

        JLabel dateLabel = new JLabel("日期：");
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        frm.add(dateLabel, constraints);
        dateText = new JTextField();
        dateText.setColumns(5);
        constraints.gridx = 3;
        constraints.weightx = 1;
        frm.add(dateText, constraints);

        JLabel ipcLabel = new JLabel("IPC：");
        constraints.gridx = 4;
        constraints.gridwidth = 1;
        frm.add(ipcLabel, constraints);
        ipcText = new JTextField();
        ipcText.setColumns(5);
        constraints.gridx = 5;
        constraints.weightx = 1;
        frm.add(ipcText, constraints);

        JLabel cpcLabel = new JLabel("CPC：");
        constraints.gridx = 6;
        constraints.gridwidth = 1;
        frm.add(cpcLabel, constraints);
        cpcText = new JTextField();
        cpcText.setColumns(5);
        constraints.gridx = 7;
        constraints.weightx = 1;
        frm.add(cpcText, constraints);

        JButton queyButton = new JButton("查询");
        constraints.gridx = 8;
//        constraints.weightx = 1;
        frm.add(queyButton, constraints);
        queyButton.addActionListener(onClickQueryBtn);


        // 查询结果
        String[] columnName = {"ID", "日期", "IPC", "CPC"};
        ChapterSix.init(corpus);
        String[][] rowData = parseTableData(corpus);
        table = new JTable(new DefaultTableModel(rowData, columnName));
        JScrollPane scrollTablePane = new JScrollPane(table);
        scrollTablePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 10;
        constraints.gridheight = 2;
        constraints.weightx = 1;
        frm.add(scrollTablePane, constraints);

        JButton addButton = new JButton("添加");
        constraints.gridx = 0;
        constraints.gridy = 3;
        constraints.gridwidth = 3;
        frm.add(addButton, constraints);
        addButton.addActionListener(onClickAddBtn);

        JButton delButton = new JButton("删除");
        constraints.gridx = 3;
        constraints.gridy = 3;
        constraints.gridwidth = 3;
        frm.add(delButton, constraints);
        delButton.addActionListener(onClickDeleteBtn);

        JButton aboutButton = new JButton("关于");
        constraints.gridx = 6;
        constraints.gridy = 3;
        constraints.gridwidth = 3;
        frm.add(aboutButton, constraints);
        aboutButton.addActionListener(onClickAboutBtn);
    }

    public void setTable(String[][] data) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);
        for (String[] row : data) {
            model.addRow(row);
        }
        table.setModel(model);
        //table.setValueAt(data[0][0], 0, 0);
    }

    public String[][] parseTableData(Corpus corpus) {
        Map<Integer, Patent> patentList = corpus.patentList;
        String[][] data = new String[patentList.size()][4];
        int i = 0;
        for (Map.Entry<Integer, Patent> entry : patentList.entrySet()) {
            Patent patent = entry.getValue();
            data[i][0] = String.valueOf(patent.getId());
            data[i][1] = String.valueOf(patent.getDate());
            data[i][2] = String.valueOf(patent.getIpcs());
            data[i][3] = String.valueOf(patent.getCpcs());
            i++;
        }
        return data;
    }

    ActionListener onClickQueryBtn = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String id, date, ipc, cpc;
            id = IDText.getText();
            date = dateText.getText();
            ipc = ipcText.getText();
            cpc = cpcText.getText();

            Corpus result = corpus;
            if (id.equals("") && date.equals("") && ipc.equals("") && cpc.equals("")) {
                setTable(parseTableData(corpus));
                return;
            }
            if (!id.equals("")) {
                result = corpus.searchPatent(Integer.parseInt(id));
            }
            if (!date.equals("")) {
                Date d = new Date(date);
                result = corpus.searchPatent(d);
            }
            if (!ipc.equals("")) {
                Ipc i = new Ipc(ipc);
                result = corpus.searchPatent(i);
            }
            if (!cpc.equals("")) {
                Cpc c = new Cpc(cpc);
                result = corpus.searchPatent(c);

            }
            setTable(parseTableData(result));
        }
    };

    ActionListener onClickDeleteBtn = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row == -1) {
                JOptionPane p = new JOptionPane();
                JOptionPane.showMessageDialog(p, "请在表格中选择一行", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                String id = (String) table.getValueAt(row, 0);
                corpus.deletePatent(Integer.parseInt(id));
                setTable(parseTableData(corpus));
            }
        }
    };

    ActionListener onClickAddBtn = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new JDialog();
            dialog.setTitle("添加专利");
            dialog.setSize(600, 200);
            dialog.setLocationRelativeTo(null);
            dialog.setModal(true);
            dialog.setResizable(true);
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

            JPanel panel = new JPanel();
            panel.setLayout(new GridLayout(4, 1));
            //panel.setBounds(10, 10, 600, 200);
            dialog.add(panel);

            JLabel idLabel = new JLabel("专利号");
            JLabel dateLabel = new JLabel("日期");
            JLabel ipcLabel = new JLabel("IPC");
            JLabel cpcLabel = new JLabel("CPC");
            JLabel position = new JLabel("Position");
            JLabel value = new JLabel("Value");

            JTextField idText = new JTextField();
            JTextField dateText = new JTextField();
            JTextField ipcText = new JTextField();
            JTextField cpcText = new JTextField();
            JTextField positionText = new JTextField();
            JTextField valueText = new JTextField();

            panel.add(idLabel);
            panel.add(idText);
            panel.add(dateLabel);
            panel.add(dateText);
            panel.add(ipcLabel);
            panel.add(ipcText);
            panel.add(cpcLabel);
            panel.add(cpcText);
            panel.add(position);
            panel.add(positionText);
            panel.add(value);
            panel.add(valueText);

            JButton okBtn = new JButton("确定");
            JButton cancelBtn = new JButton("取消");

            panel.add(okBtn);
            panel.add(cancelBtn);

            okBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String id = idText.getText();
                    String date = dateText.getText();
                    String ipc = ipcText.getText();
                    String cpc = cpcText.getText();
                    String position = positionText.getText();
                    String value = valueText.getText();

                    if (id.equals("") || date.equals("") || ipc.equals("") || cpc.equals("")) {
                        JOptionPane p = new JOptionPane();
                        dialog.dispose();
                        JOptionPane.showMessageDialog(p, "请填写完整信息", "提示", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        try {
                            corpus.add(new Patent(Integer.parseInt(id), date, ipc, cpc, position.charAt(0), value.charAt(0)));
                        } catch (Exception ex) {
                            JOptionPane p = new JOptionPane();
                            dialog.dispose();
                            JOptionPane.showMessageDialog(p, "专利信息输入错误", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                        setTable(parseTableData(corpus));
                        dialog.dispose();
                    }
                }
            });
            cancelBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                }
            });

            dialog.setVisible(true);
        }
    };

    ActionListener onClickAboutBtn = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String info = "JAVA语言课程大作业\n" +
                    "Copyright © 2022 熊浩男\n" +
                    "感谢徐硕老师的指导";
            JOptionPane.showMessageDialog(null, info, "关于", JOptionPane.INFORMATION_MESSAGE);
        }
    };
}